<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\admin\model;

use think\Model;

class Admin extends Model
{
    public function getAdmin($id){   //传入id 获得当前id的记录，传null 获得所有记录的列表
      if($id){
          return $this->where('id',$id)->find();
      }else{
          return $this->paginate(10);
      }
      
      
  }

    public function addAdmin($data){
        $adminData=array();
        $adminData['username']=$data['username'];
        $adminData['password']=$data['password'];
        if($this->save($adminData)){
            $group_access['uid']=$this->id;
            $group_access['group_id']=$data["group_id"];
            db('auth_group_access')->insert($group_access);
            return TRUE;
        } else {
            return FALSE;
        }
  }
  
    public function deleteAdmin($id){
       if($this->destroy($id))
       {
           return TRUE;
       }else{
           return FALSE;
       }
   }
   
    public function saveAdmin($data){
         if(empty($data)|| !is_array($data)){
            return false;
        }

        $adminData=array();
        $adminData['id']=$data['id'];
        $adminData['username']=$data['username'];
        $adminData['password']=$data['password'];

        if($this->update($adminData)){
            if(db('auth_group_access')->where("uid",$data['id'])->find()){
                db('auth_group_access')->where("uid",$data['id'])->update(['group_id'=>$data["group_id"]]);
            }else{
                $group_access['uid']=$data['id'];
                $group_access['group_id']=$data["group_id"];
                db('auth_group_access')->insert($group_access);
            }

            return true;
        }else{
            return false;
        }
   }

    public function loginAdmin($data){
        $user = $this->where(['username' => $data['username']])->find();
//          $user = $this->getByName($data['username']);
          if($user){
              if( $user['password']===md5($data['password']) ){
                  session('id',$user['id']);
                  session('username',$user['username']);

                  return 2;//登录成功
              }
              else{
                  return 3; //密码错误
              }

          }else{
              return 1;//未找到用户；
          }

    }


   
}